package com.xm.adv.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

/**
 * Created by zhangjiebo on 2019/5/14.
 *
 * @author ZhangJieBo
 */
public class MyRelativeLayout extends RelativeLayout {

    private float x;
    private float minScroll = 30;
    private float xx;

    public MyRelativeLayout(Context context) {
        super(context);
    }

    public MyRelativeLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRelativeLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = ev.getX();
                return false;
            case MotionEvent.ACTION_MOVE:
                float xMove = ev.getX();
                if (Math.abs(xMove - x) > minScroll) {
                    return true;
                }
                return false;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float xMove = event.getX();
                if (onScrollDistanceListener != null) {
                    onScrollDistanceListener.scrollDistance((xMove - x));
                }
                return true;
            case MotionEvent.ACTION_UP:
                float xMove1 = event.getX();
                if (onScrollDistanceListener != null) {
                    onScrollDistanceListener.scrollCancle((xMove1 - x));
                }
                return true;
            case MotionEvent.ACTION_CANCEL:
                float xMove2 = event.getX();
                if (onScrollDistanceListener != null) {
                    onScrollDistanceListener.scrollCancle((xMove2 - x));
                }
                return true;
        }
        return super.onTouchEvent(event);
    }

    public interface OnScrollDistanceListener {
        void scrollDistance(float distance);
        void scrollCancle(float distance);
    }

    OnScrollDistanceListener onScrollDistanceListener;

    public void setOnScrollDistanceListener(OnScrollDistanceListener onScrollDistanceListener) {
        this.onScrollDistanceListener = onScrollDistanceListener;
    }

}
